package com.netty.chapter07;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HelloWordServer {
    public static void main(String[] args) {

        // 创建时间循环对象
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker=new NioEventLoopGroup();
        // 创建服务启动对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.option(ChannelOption.SO_RCVBUF,10);
        serverBootstrap.group(boss,worker);
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG){
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println(((ByteBuf) msg));
                        super.channelRead(ctx, msg);
                    }
                });
            }
        });
        ChannelFuture serveFuture = serverBootstrap.bind(8080);
        // 连接建立成功触发的监听时间
        serveFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        // 连接关闭事件触发
                        boss.shutdownGracefully();
                        worker.shutdownGracefully();
                    }
                });
            }
        });
    }
}
